package com.web.tasks;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.web.common.Sys;
import com.web.model.PageBean;
import com.web.model.TCathectic;
import com.web.model.TUser;
import com.web.model.TUserBalanceRecord;
import com.web.model.TWinNum;
import com.web.model.TWinResult;
import com.web.model.constant.Constant;
import com.web.service.TCathecticService;
import com.web.service.TUserBalanceRecordService;
import com.web.service.TUserService;
import com.web.service.TWinNumService;
import com.web.service.TWinResultService;
import com.web.service.TWinTypeService;
import com.web.utils.HttpRequest;
import com.web.utils.HttpTest;
import com.web.utils.WinNumUtil;
/**
 * 安全开奖类    暂定一小时跑一次，每次15期，涵盖已小时内的数据
 * 用于定时获取其他接口中的返回数据，自动开奖
 * 在部署用户访问项目的时候，注释掉类上面的@Component
 * 
 */
//@Component
public class RefreshWinNumSafeTask extends AbstractTask{

	protected RefreshWinNumSafeTask() {
		super("refresh winnum safe", true);
	}

	@Autowired
	private TUserService userService;

	@Autowired
	private TWinNumService winNumService;
	
	@Autowired
	private TWinTypeService winTypeService;
	
	@Autowired 
	private TWinResultService winResultService;
	
	@Autowired
	private TCathecticService cathecticService;
	
	@Autowired
	private TUserBalanceRecordService userBalanceRecordService;
	
	@Resource(name="sys")
	private Sys sys;
	
	@Resource(name="winNumUtil")
	private WinNumUtil winNumUtil;

	private String jsonResult;


	private JSONObject jsonObject;
	private TWinNum insertWinNum = new TWinNum();
	private TWinNum resultWinNum;
	private String nums;
	private String[] numArr;
	private Long termcd;
	private Calendar cal;
	private Map<String, Object> param = new HashMap<String, Object>();
	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	PageBean<TWinNum> winNumPage;
	private JSONArray jsonArray;

	//0 */1 * * * ?  测试环境使用
	//0/4 * * * * ?  生产使用
	@Override
	@Scheduled(cron = "0 0 0/1 * * ?")
	public void taskEntrance() {
		super.taskEntrance();
	}

	@Override
	protected void executeTask() {
		cal = Calendar.getInstance();
		int currH = cal.get(Calendar.HOUR_OF_DAY);
		if(currH > 0 && currH <= 9){ //没结果时间段
			logger.info("休息时段，不请求结果");
			return;
		}
		logger.info("================ 获取开奖结果 ==================");
		jsonResult = HttpTest.get(HttpRequest.pkUrl, HttpTest.charset);
		checkResult(jsonResult);
		
	}
	
	/**
	 * 处理获取到的json，和库里的数据做对比
	 * 怕有遗漏，获取开奖数据取15期，库中结果取20期做对比
	 * @param jsonResult
	 */
	private void checkResult(String jsonResult) {
		param.clear();
		param.put("pageNum", 1);
		param.put("pageSize", 20);
		winNumPage = winNumService.selectListByPage(param); 
		jsonObject = JSONObject.parseObject(jsonResult);// 转化为JSON类
		jsonArray = jsonObject.getJSONArray("data");
		boolean flag;
		for (int i = 0; i < jsonArray.size(); i++) {
			jsonObject = jsonArray.getJSONObject(i);
			flag = false;
			if(i == 0){ //最新一期不比对
				continue;
			}
			termcd = jsonObject.getLongValue("expect");
			for (TWinNum  w: winNumPage.getList()) {
				if(termcd.equals(w.getTermCd())){//存在
					flag =true;
				}
			}
			if(!flag){
				insertWinNum(jsonObject, termcd);// 先入库
				winNumUtil.checkWinNum(insertWinNum,numArr);
			}
		}
	}

	private void insertWinNum(JSONObject jsonObj, long termcd) {
		try {
			//插库
			nums = jsonObj.getString("opencode");
			numArr = nums.split(",");
			insertWinNum.setNum1(numArr[0]);
			insertWinNum.setNum2(numArr[1]);
			insertWinNum.setNum3(numArr[2]);
			insertWinNum.setNum4(numArr[3]);
			insertWinNum.setNum5(numArr[4]);
			insertWinNum.setNum6(numArr[5]);
			insertWinNum.setNum7(numArr[6]);
			insertWinNum.setNum8(numArr[7]);
			insertWinNum.setNum9(numArr[8]);
			insertWinNum.setNum10(numArr[9]);
			insertWinNum.setWinTime(sdf.parse(jsonObj.getString("opentime")));
			insertWinNum.setTermCd(termcd);
			resultWinNum = winNumService.selectByPrimaryKey(termcd);
			if(resultWinNum == null){
				winNumService.insert(insertWinNum);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	@PostConstruct
	public void init(){
		jsonResult = HttpTest.get(HttpRequest.pkUrl, HttpTest.charset);
		System.out.println(jsonResult);
		checkResult(jsonResult);
	}
}
	
